package cn.edu.abc.wangzi.fragment;
/*
 *  项目名：Wangzi
 *  包名：cn.edu.abc.wangzi.fragment
 *  创建者：SKFsky
 *  创建时间：2017/8/20 22:56
 *  描述:   语音聊天机器人
 */

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.edu.abc.wangzi.R;
import cn.edu.abc.wangzi.adapter.ChatListAdapter;
import cn.edu.abc.wangzi.entity.ChatListData;
import cn.edu.abc.wangzi.utils.L;
import cn.edu.abc.wangzi.utils.ShareUtils;
import cn.edu.abc.wangzi.utils.StaticClass;

public class ButlerFragment extends Fragment implements View.OnClickListener {

    private ListView mChatListView;
    private List<ChatListData> mList = new ArrayList<>();
    private ChatListAdapter adapter;
    private SpeechSynthesizer mTts;

    //输入框
    private EditText et_text;
    //发送按钮
    private Button btn_send;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_butler, null);
        findView(view);
        return view;
    }

    private void findView(View view) {

        //1.创建SpeechSynthesizer对象
        mTts = SpeechSynthesizer.createSynthesizer(getActivity(), null);
        //2.合成参数设置，详见《MSC Reference Manual》SpeechSynthesizer 类
        mTts.setParameter(SpeechConstant.VOICE_NAME, "xiaoyan");//设置发音人
        mTts.setParameter(SpeechConstant.SPEED, "50");//设置语速
        mTts.setParameter(SpeechConstant.VOLUME, "80");//设置音量，范围0~100

        mChatListView = (ListView) view.findViewById(R.id.mChatListView);
        et_text = (EditText) view.findViewById(R.id.et_text);
        btn_send = (Button) view.findViewById(R.id.btn_send);
        btn_send.setOnClickListener(this);
        adapter = new ChatListAdapter(getActivity(), mList);
        mChatListView.setAdapter(adapter);
        addLeftItem("你好，我是小玲");

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onClick(View view) {
        String text = et_text.getText().toString();
        if (!TextUtils.isEmpty(text)) {
            if (text.length() > 30) {
                Toast.makeText(getActivity(), "输入长度超出限制", Toast.LENGTH_SHORT).show();
            } else {
                et_text.setText("");
                addRightItem(text);
                String url = "http://op.juhe.cn/robot/index?info=" + text
                        + "&key=" + StaticClass.CHAT_LIST_KEY;
                RxVolley.get(url, new HttpCallback() {
                    @Override
                    public void onSuccess(String t) {
                        //Toast.makeText(getActivity(), "Json:" + t, Toast.LENGTH_SHORT).show();
                        L.i("Json" + t);
                        parsingJson(t);
                    }
                });
            }
        } else {
            Toast.makeText(getActivity(), "输入框不能为空", Toast.LENGTH_SHORT).show();
        }
    }

    private void parsingJson(String t) {
        try {
            JSONObject jsonObject = new JSONObject(t);
            JSONObject jsonResult = jsonObject.getJSONObject("result");
            String text = jsonResult.getString("text");
            addLeftItem(text);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    //添加左边文本
    private void addLeftItem(String text) {

        boolean isSpeak = ShareUtils.getBoolean(getActivity(), "isSpeak", false);
        if (isSpeak){
            startSpeak(text);
        }
        ChatListData date = new ChatListData();
        date.setType(1);
        date.setText(text);
        mList.add(date);
        adapter.notifyDataSetChanged();
        mChatListView.setSelection(mChatListView.getBottom());
    }

    //添加右边文本
    private void addRightItem(String text) {
        ChatListData date = new ChatListData();
        date.setType(2);
        date.setText(text);
        mList.add(date);
        adapter.notifyDataSetChanged();
        mChatListView.setSelection(mChatListView.getBottom());
    }

    private void startSpeak(String text) {
        mTts.startSpeaking(text, mSynListener);
    }

    //合成监听器
    private SynthesizerListener mSynListener = new SynthesizerListener() {

        //会话结束回调接口，没有错误时，error为null
        public void onCompleted(SpeechError error) {
        }

        @Override
        public void onEvent(int i, int i1, int i2, Bundle bundle) {

        }

        //缓冲进度回调
        //percent为缓冲进度0~100，beginPos为缓冲音频在文本中开始位置，endPos表示缓冲音频在文本中结束位置，info为附加信息。
        public void onBufferProgress(int percent, int beginPos, int endPos, String info) {
        }

        //开始播放
        public void onSpeakBegin() {
        }

        //暂停播放
        public void onSpeakPaused() {
        }

        //播放进度回调
        //percent为播放进度0~100,beginPos为播放音频在文本中开始位置，endPos表示播放音频在文本中结束位置.
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
        }

        //恢复播放回调接口
        public void onSpeakResumed() {
        }
    };
}
